<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="政策标题" prop="policyTitle">
        <el-input v-model="queryParams.title" placeholder="请输入政策标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="申请人" prop="creatorName">
        <el-input v-model="queryParams.creatorName" placeholder="请输入申请人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" placeholder="请输入审核状态" clearable @keyup.enter="handleQuery"
          style="width: 180px;">
          <el-option label="待审核" value="0" />
          <el-option label="通过" value="1" />
          <el-option label="驳回" value="2" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="${comment}" prop="approveTime">
                            <el-date-picker clearable
                                            v-model="queryParams.approveTime"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                                            placeholder="请选择${comment}">
                            </el-date-picker>
                        </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['bus:policyApprove:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['bus:policyApprove:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['bus:policyApprove:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['bus:policyApprove:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->

    <el-table v-loading="loading" :data="policyApproveList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="政策标题" align="center" prop="title" width="200" />
      <el-table-column label="政策内容" align="center" prop="content">
        <template #default="scope">
          <el-button link type="primary" @click="handleContentViewDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="政策申请人" align="center" prop="creatorName" />
      <el-table-column label="审批状态" align="center" prop="approveStatus">
        <template #default="scope">
          <el-tag :type="getApproveStatusTagType(scope.row.approveStatus)">
            {{ getApproveStatusLabel(scope.row.approveStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-if="scope.row.approveStatus === 1" v-hasPermi="['bus:policyApprove:edit']">审核</el-button>
          <el-button link type="primary" icon="View" @click="handleViewDetail(scope.row)"
            v-if="scope.row.approveStatus !== 1">查看审核信息</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bus:policyApprove:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改政策审核对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="policyApproveRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="${comment}" prop="policyId">
                                    <el-input v-model="form.policyId" placeholder="请输入${comment}" />
                                </el-form-item> -->
        <!-- <el-form-item label="${comment}" prop="approverId">
                                    <el-input v-model="form.approverId" placeholder="请输入${comment}" />
                                </el-form-item> -->

        <!-- <el-form-item label="审核状态" prop="approveStatus">
          <el-radio-group v-model="form.approveStatus">
            <el-radio v-for="item in approveStatusOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="审核意见" prop="approveReview" required>
          <el-input v-model="form.approveReview" type="textarea" :rows="4" :maxlength="200" show-word-limit
            placeholder="请输入审核意见" @keydown="handleKeydown" @input="handleInput" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleApprove(0)">通 过</el-button>
          <el-button @click="handleApprove(2)">驳 回</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 政策内容详情对话框 -->
    <el-dialog :title="policyTitle" v-model="policyOpen" width="800px" append-to-body>
      <div class="detail-content">
        <div v-html="policyContent" class="rich-text-content"></div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="policyOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="审核详情" v-model="detailOpen" width="500px" append-to-body>
      <el-form :model="detailForm" label-width="80px">
        <el-form-item label="审核状态:">
          <el-tag :type="getApproveStatusTagType(detailForm.approveStatus)">
            {{ getApproveStatusLabel(detailForm.approveStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核意见:">
          <el-input type="textarea" :rows="4" v-model="detailForm.approveReview" readonly>
          </el-input>
        </el-form-item>
        <el-form-item label="审核时间:">
          <span>{{ parseTime(detailForm.approveTime, '{y}-{m}-{d}') }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PolicyApprove">
  import {
    listPolicyApprove,
    getPolicyApprove,
    delPolicyApprove,
    addPolicyApprove,
    updatePolicyApprove
  } from "@/api/bus/policyApprove";

  const {
    proxy
  } = getCurrentInstance();

  const policyApproveList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const policyTitle = ref("");
  const policyContent = ref("");

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      policyId: null,
      approverId: null,
      approveStatus: null,
      approveReview: null,
      approveTime: null
    },
    rules: {
      approveReview: [{
        required: true,
        message: '审核意见不能为空',
        trigger: 'blur'
      }]
    }
  });

  const {
    queryParams,
    form,
    rules
  } = toRefs(data);

    const approveStatusOptions = [{
      label: '通过',
      value: 0
    },
    {
      label: '拒绝',
      value: 2
    }
  ];

  // 审核状态映射关系
  const approveStatusMap = {
    0: {
       label: '已通过',
      type: 'success'
    },
    1: {
      label: '待审核',
      type: 'warning'
    },
    2: {
      label: '已驳回',
      type: 'danger'
    }
  };

  // 获取标签显示文字
  function getApproveStatusLabel(value) {
    return approveStatusMap[value]?.label || '未知状态';
  }

  // 获取标签样式类型（用于 el-tag 的 type 属性）
  function getApproveStatusTagType(value) {
    return approveStatusMap[value]?.type || 'warning';
  }

  const policyOpen = ref(false);
  /** 查看详情按钮操作 */
  function handleContentViewDetail(row) {
    policyTitle.value = row.title;
    policyContent.value = row.content || '';
    policyOpen.value = true;
  }
  /** 查询政策审核列表 */
  function getList() {
    loading.value = true;
    listPolicyApprove(queryParams.value).then(response => {
      policyApproveList.value = response.rows || [];
      total.value = response.total || 0;
      loading.value = false;
    }).catch(error => {
      loading.value = false;
      proxy.$modal.msgError('数据加载失败: ' + (error.msg || '网络错误'));
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      approveId: null,
      policyId: null,
      approverId: null,
      approveStatus: null,
      approveReview: null,
      approveTime: null
    };
    proxy.resetForm("policyApproveRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.approveId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加政策审核";
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _policyId = row.policyId || ids.value
    getPolicyApprove(_policyId).then(response => {
      form.value = response.data;
      // 确保审核状态有默认值
      if (form.value.approveStatus === undefined || form.value.approveStatus === null) {
        form.value.approveStatus = 1;
      }
      open.value = true;
      title.value = "修改政策审核";
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["policyApproveRef"].validate(valid => {
      if (valid) {
        if (form.value.approveId != null) {
          updatePolicyApprove(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addPolicyApprove(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _approveIds = row.approveId || ids.value;
    proxy.$modal.confirm('是否确认删除政策审核编号为"' + _approveIds + '"的数据项？').then(function() {
      return delPolicyApprove(_approveIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('bus/policyApprove/export', {
      ...queryParams.value
    }, `policyApprove_${new Date().getTime()}.xlsx`)
  }

  getList();

  // 添加详情相关变量
  const detailOpen = ref(false);
  const detailForm = ref({});

  // 查看详情按钮操作
  function handleViewDetail(row) {

    const _policyId = row.policyId || ids.value
    getPolicyApprove(_policyId).then(response => {
      detailForm.value = response.data;
    });
    detailOpen.value = true;
  }

  function handleApprove(status) {
    form.value.approveStatus = status;
    submitForm();
  }
</script>